const fs = require("fs");
const path = require("path");

const marked = require("marked");
const browserSync = require("browser-sync");

/**
 * 01. 读取md 和css中的内容
 * 02. 将上述读取的内容替换占位符， 生成一个最终需要展示的html字符串
 * 03. 将上述的html字符写入到指定的html文件中
 * 04. 监听md文档 内容的变化， 然后更新html内容
 * 05. 使用browser-sync来将html展示到浏览器中
 */

let mdPath = path.join(__dirname, process.argv[2]);
let cssPath = path.resolve("github.css");
let htmlPath = mdPath.replace(path.extname(mdPath), ".html");

console.log(mdPath);
console.log(cssPath);
console.log(htmlPath);

fs.watchFile(
  mdPath,
  {
    interval: 1000,
  },
  (curr, prev) => {
    if (curr.mtime !== prev.mtime) {
      handleMdFile();
    }
  }
);

function handleMdFile() {
  fs.readFile(mdPath, "utf-8", (err, data) => {
    // 将md 转为html
    let htmlStr = marked(data);
    fs.readFile(cssPath, "utf-8", (err, data) => {
      let retHtml = template
        .replace("{{content}}", htmlStr)
        .replace("{{style}}", data);
      // 将上述的内容写入到指定的html文件中， 用于在浏览器中进行展示
      fs.writeFile(htmlPath, retHtml, (err) => {
        console.log("html 生成成功了");
      });
    });
  });
}

browserSync.init({
  browser: "",
  server: __dirname,
  watch: true,
  index: path.basename(htmlPath),
});

var template = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>{{style}}</style>
</head>
<body>
    {{content}}
</body>
</html>
`;
